<template>
  <div>
    <el-input v-model="url" readonly placeholder="请上传图片" class="imginput">
      <template slot="append">
        <div class="commhover full_w inputbox">
          上传图片
          <input
            type="file"
            name=""
            class="uploadinput commhover"
            id="uploadimg"
            accept="image/*"
            @change="changeImg"
          />
        </div>
      </template>
    </el-input>
    <div v-if="imgsrc" class="mt_12">
      <el-image :src="imgsrc" :preview-src-list="[imgsrc]" :style="{width:imgwidth,height:imgheight}"></el-image>
    </div>
  </div>
</template>
<script>
import { isOverSize } from "@/utils/validate";
import { uploadPhoto } from "@/api/comm";
export default {
  data() {
    return {
      url: "",
      imgsrc: "",
      dialogVisible:false,
      dialogImageUrl:'',
    };
  },
  props: {
    value: "",
    imgwidth:{
        type:String,
        default:"120px"
    },
    imgheight:{
        type:String,
        default:"auto"
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.url = val
          this.imgsrc = val.startsWith("http")? val : this.domain + "/" + val
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    // 上传图片
    changeImg(event) {
      var file = event.currentTarget.files[0];
      console.log("file:", file, event);
      if (isOverSize(file.size, 5)) {
        this.$message.warning("图片大小不能超过5MB");
        return;
      }
      var formData = new FormData();
      formData.append("file", file);
      formData.append("type", "adv");
      uploadPhoto(formData).then((res) => {
        if (res.code == 1) {
          this.$message.success("上传成功");
          this.url = res.data.url;
          this.imgsrc = this.url.startsWith("http") ? res.data.url: this.domain + "/" + res.data.url;
          document.getElementById("uploadimg").value = null;
          this.uploadedSuccessfully();
        }
      });
    },

    uploadedSuccessfully() {
      this.$emit("input", this.url);
    },

    // 预览
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.imginput {
  ::v-deep .el-input-group__append {
    padding: 0 !important;
  }
  ::v-deep .el-input-group__append{
    background-color: #1670F1;
    border: 1px solid #1670F1;
    color: #fff;
  }

}
.inputbox {
  position: relative;
  padding: 0 20px;
  cursor: pointer;

}
.uploadinput {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  cursor: pointer;
}
.imgurl {
  width: 120px;
  height: 200px;
}
</style>